//$Id: RegisterAction.java 5509 2007-06-25 16:19:40Z gavin $
package org.jboss.seam.example.jpa;

import static org.jboss.seam.ScopeType.EVENT;

import java.util.List;

import javax.persistence.EntityManager;


import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

@Scope(EVENT)
@Name("register")
public class RegisterAction
{

   @In
   private User user;
   
   @In
   private EntityManager em;
   
   @In
   private FacesMessages facesMessages;
   
   private String verify;
   
   private boolean registered;
   
   @Logger 
   private Log log;
   
  // @End
   public void register()
   {      
	   
	   if ( user.getPassword().equals(verify) )
   {
       List existing = em.createQuery("select u.username from User u where u.username=#{user.username}")
          .getResultList();
       if (existing.size()==0)

       {
    	  log.info("Calling persist...");
    	  
          em.persist(user);
          

          
          log.info("User "+ user.getUsername()+ " persisted");
          facesMessages.add("Successfully registered as #{user.username}");
          registered = true;
       }
       else
       {
    	   System.out.println("Username " +user.getName()+ " already exists");
    	   
//    	  facesMessages.addToControl("username", "Username" +user2.getName()+ "already exists");
//    	   
          facesMessages.addToControl("Username #{user.username} already exists","username");
    	   facesMessages.addToControl( "Username #{user.username} already exists", "register:usernameDecorate:username");
    	   facesMessages.addToControl( "username", "Username #{user.username} already exists" );
    	   facesMessages.addToControl( "register:username", "Username #{user.username} already exists" );
    	   facesMessages.addToControl("Username #{user.username} already exists","register:username");
    	   facesMessages.addToControl("register:usernameDecorate:username", "Username #{user.username} already exists");
    	//   facesMessages.addToControlFromResourceBundle("verify", "TEKKKST");
    	 //  facesMessages.addToControlFromResourceBundle("verify", "TEKKKST");
       }
    }
    else 
    {
      // facesMessages.add("Re-enter your password");
       facesMessages.addToControl("verify", "Re-enter your password");
       verify=null;
    }  
	   
   }
   
   public void invalid()
   {
      facesMessages.add("Please try again");
   }
   
   public boolean isRegistered()
   {
      return registered;
   }
 //  @Begin(flushMode=FlushModeType.MANUAL)
   public String getVerify()
   {
      return verify;
   }

   public void setVerify(String verify)
   {
      this.verify = verify;
   }
   
}
